package com.iqiyi.pps.epg.api.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by karkarrotxu on 2014/12/10.
 */
public final class ApiHttpRequestUtil {
    private static Logger logger = LoggerFactory.getLogger(ApiHttpRequestUtil.class);
    public static final int HTTP_TIMEOUT = 5000;

    private ApiHttpRequestUtil(){}

    public static  String postMethod(String url,Map<String,? extends Object> headers,Map<String,? extends Object> params){
        Long startTime = System.currentTimeMillis();
        HttpClientConnection connection = null;
        String result = null;
        for (int i = 0; i < 3; i++) {
            connection = new HttpClientConnection(url, HttpClientConnection.POST_METHOD);
            if (headers != null && headers.size()>0) {
                connection.setReqHeaders(headers);
            }
            connection.setReqParams(params);
            connection.setSoTimeout(5000);
            connection.connect();
            logger.info("[HTTP][postMethod][url:{}][params:{}][status:{}]", new Object[]{url, JSON.toJSONString(params),connection.getStatus()});
            if (connection.getStatus() == 200) {
                result = connection.getBody();
                logger.info("[HTTP][postMethod][response:{}]", connection.getBody());
                return result;
            }
        }
        logger.info("[HTTP][postMethod][cost:{}]", System.currentTimeMillis() - startTime);
        return result;
    }


    public static String postMethod(String url,Map<String,? extends Object> params) {
        return postMethod(url,null,params);
    }

    public static String getMethod(String url,Map<String,? extends Object> headers,Map<String,? extends Object> params) {
        Long startTime = System.currentTimeMillis();
        HttpClientConnection connection = null;
        String result = null;
        for (int i = 0; i < 3; i++) {
            connection = new HttpClientConnection(url, HttpClientConnection.GET_METHOD);
            if(headers != null &&headers.size() > 0){
                connection.setReqHeaders(headers);
            }
            if(params != null &&params.size() > 0){
                connection.setReqParams(params);
            }

            connection.setSoTimeout(30000);
            connection.connect();
            logger.info("[HTTP][getMethod][url:{}][params:{}][status:{}]", new Object[]{url, JSON.toJSONString(params),connection.getStatus()});
            if (connection.getStatus() == 200) {
                result = connection.getBody();
                logger.info("[HTTP][getMethod][response:{}]", connection.getBody());
                return result;
            }
        }
        logger.info("[HTTP][getMethod][cost:{}]", System.currentTimeMillis() - startTime);
        return result;
    }

    public static JSONObject doPostRaw(String url, String jsonParams) {
        JSONObject data = null;
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;

        try {
            httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
            httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new StringEntity(jsonParams,"UTF-8"));
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(httpPost);
            String content = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(content);
            data = jsonObject;
            logger.info("[HTTP][postMethod][url:{}][params:{}]", new Object[]{url, jsonParams});
        } catch(Exception e) {
            return new JSONObject();
        }
        return data;
    }

    public static String originalPost(String url, Map<String, ? extends Object> params, Map<String, ? extends Object> headers) {
        return postMethod(url, transMap(headers), transMap(params));
    }

    private static Map<String, String> transMap(Map<String, ? extends Object> map) {
        if (map == null) {
            return null;
        }
        Map<String, String> keyMap = new HashMap<String, String>();
        for (Map.Entry<String, ? extends Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                keyMap.put(entry.getKey(), entry.getValue() + "");
            }
        }
        return keyMap;
    }

    public static Map<String, Object> getEpgHeaders() {
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("From","show");
        headers.put("Sign", "#f93Uc31K24()_@");
        return headers;
    }
}
